local mysql = require "mysql"

local _M = {}

local function close_db(db) 
  if not db then 
    return
  end
  db:close()
end

local db, err = mysql:new()
if not db then 
  ngx.log(ngx.ERR, "new mysql error :" .. err)
  return
end
db:set_timeout(1000)

_M.db = db

local props = {
  host = "192.168.0.103",
  port = 3306,
  database = "passport",
  user = "passport",
  password = "passport"
}

local res, err, errno, sqlstate = db:connect(props)

if not res then 
  ngx.log(ngx.ERR, "connect to mysql error : " .. err .. " , errno : " ..  errno .. " , sqlstate : " .. sqlstate)
  return close_db(db)
end

_M.query = function(self, sql) 
  local res, err, errno, sqlstate = self.db:query(sql)
  if not res then 
    ngx.log(ngx.ERR, "connect to mysql error : " .. err .. " , errno : " ..  errno .. " , sqlstate : " .. sqlstate)
    return close_db(db)
  end
  return res
end

return _M
